#include "proxy_local.h"
#include "proxy_exports.h"
#include "proxy_functionimport.h"
#include "../jagamex86/bg_hooks.h"
#include "../jagamex86/bg_global.h"

CDECL_FUNCTION(gentity_t *, CreateMissileEx, ( vec3_t mzle, vec3_t fwd, float velocity, int life, gentity_t *owner ));
CDECL_FUNCTION(void, WP_EmplacedGunFireX, ( gentity_t *ent ) );

CreateMissileEx CreateMissile;
WP_EmplacedGunFireX WP_EmplacedGunFire;

void WP_TieFighterFire ( gentity_t *ent );

vec3_t muzzle;
vec3_t forward;

int weaponNum;
static unsigned int returnAddress1;

void FireAppropriateWeaponFunc ( gentity_t *ent )
{
	WP_TieFighterFire(ent);
}

__declspec(naked) void FireWeaponHook(void)
{
	__asm 
	{
		call FireAppropriateWeaponFunc
		add esp,4
		jmp returnAddress1
	}
}

void AlterWeaponDamages( void )
{
	//Get some func calls set up
	CreateMissile = (CreateMissileEx)(DLLA(0x200A2C80, jagamex86));
	WP_EmplacedGunFire = (WP_EmplacedGunFireX)(DLLA(0x200A3A10, jagamex86));

	//Global vars
	muzzle[0] = (float)(DLLA(0x205842F8, jagamex86));
	forward[0] = (float)(DLLA(0x2058431C, jagamex86));
	muzzle[1] = (float)(DLLA(0x205842FC, jagamex86));
	forward[1] = (float)(DLLA(0x20584321, jagamex86));
	muzzle[2] = (float)(DLLA(0x20584301, jagamex86));
	forward[2] = (float)(DLLA(0x20584325, jagamex86));

	//Repeater
	//16 damage for main fire
	PATCH(DLLA(0x200A4EA8, jagamex86), unsigned char, 16);
	//Hook a function
	//returnAddress1 = (unsigned int)DLLA(0x200A91C1, jagamex86);
	//HOOK_JUMP(PHOOK_WEAPON1, DLLA(0x200A9186, jagamex86), FireWeaponHook);
}

void WP_TieFighterFire ( gentity_t *ent )
{
	int damage = (ent->NPC) ? 20 : 125; //Seems pretty healthy ~eezstreet
	float vel = 6000.0f;
	gentity_t *missile = CreateMissile(muzzle, forward, vel, 10000, ent);
	missile->classname = "emplaced_proj";
	if(!Q_stricmp(ent->classname, "misc_panel_turret"))
	{
		missile->damage = ent->damage;
		VectorSet2(&missile->maxs, 10.0f);
		VectorSet2(&missile->mins, -10.0f);
	}
	else
	{
		missile->damage = damage;
		VectorSet2(&missile->maxs, 5.0f);
		VectorSet2(&missile->mins, -5.0f);
	}
	missile->dflags = 4224;
	missile->methodOfDeath = MOD_EMPLACED;
	*(DWORD *)((DWORD)missile + 196) = WP_BLASTER;
	missile->clipmask = 267137;

	if(ent && ent->client && !(*((DWORD *)ent->client + 108) & 0x40000))
	{
		missile->owner = ent;
	}
	else
	{
		missile->owner = ent->owner;
	}
}